/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmooc.servlets;

import com.jmooc.entity.User;
import com.jmooc.service.UserService;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Group
 */
@WebServlet(name = "ProfileServlet", urlPatterns = {"/profile"})
public class ProfileServlet extends HttpServlet {

    @EJB
    private UserService userService;
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String mail = req.getParameter("email");
        String password = req.getParameter("password");
        String firstName = req.getParameter("firstName");
        String lastName = req.getParameter("lastName");
        String confirmPassword = req.getParameter("passwordConfirm");
        HttpSession session = req.getSession();
        User u = userService.getById((Long) session.getAttribute("userId"));
        
        if (!mail.equals("")) {
            try {
                u.setEmail(mail);
                
                if (!password.equals("") && password.equals(confirmPassword))
                    u.setPassword(password);
                
                u.setFirstName(firstName);
                u.setLastName(lastName);

                req.setAttribute("email", mail);
                req.setAttribute("firstName", u.getFirstName());
                req.setAttribute("lastName", u.getLastName());
                req.setAttribute("userId", u.getId());
                
                userService.update(u);
            } catch (Exception e) {
                req.setAttribute("message", "Addresse mail déjà existante");
            }
        } else {
            req.setAttribute("message", "Vous devez entrer un mail correct");
        }
            
        session.setAttribute("user", u);
        RequestDispatcher rd = req.getRequestDispatcher("/jsp/profile.jsp");
        rd.forward(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        
        User u = userService.getById((Long) session.getAttribute("userId"));
                
        session.setAttribute("user", u);
        RequestDispatcher rd = req.getRequestDispatcher("/jsp/profile.jsp");
        rd.forward(req, resp);
    }
}

